import download from '@/utils/download'

// "excel" | "word" | "zip" | "html" | "markdown"
type DownloadFileType = keyof typeof download

export const useDownload = (
  api: (params: any) => Promise<any>, // 改为接受一个返回 Promise<any> 的函数
  fileName: string,
  fileType: DownloadFileType = 'excel', // 使用定义的类型
  isNotify: boolean = true
) => {
  const downLoading = ref<boolean>(false)

  const downloadFile = async (searchParams?: any) => {
    if (isNotify) {
      ElNotification({
        title: '温馨提示',
        message: '如果数据庞大会导致下载缓慢哦，请您耐心等待！',
        type: 'info',
        duration: 3000,
      })
    }
    downLoading.value = true
    try {
      const res: Blob = await api(searchParams)
      if (typeof download[fileType] !== 'function') {
        throw new Error(`Invalid file type: ${fileType}`)
      }
      download[fileType](res, fileName)
    } catch (error) {
      console.error('Download failed:', error)
      ElNotification({
        title: '下载失败',
        message: '文件下载失败，请稍后再试！',
        type: 'error',
        duration: 5000,
      })
    } finally {
      downLoading.value = false
    }
  }

  return {
    downLoading,
    downloadFile,
  }
}
